package com.hibuy.pc.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;

/**
 * Created by admin on 2017/2/7.
 */
public class JsonUtil {


    private final static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * @param json
     * @param javaType
     * @return
     */
    public static Object JsonToObject(String json, JavaType javaType) {
        Object object = null;
        try {
            object = objectMapper.readValue(json, javaType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

    /**
     * @param json
     * @param javaType
     * @return
     */
    public static <T> T JsonToObject(String json, Class<T> javaType) {

        try {
            return objectMapper.readValue(json, javaType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取泛型的Collection Type
     *
     * @param collectionClass
     * @param elementClasses
     * @return
     */

    public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

    /**
     * 将json array反序列化为对象
     *
     * @param json
     * @param jsonTypeReference
     * @return
     */
    public static <T> T jsonArrayToObject(String json, TypeReference<T> jsonTypeReference) {

        try {
            return objectMapper.readValue(json, jsonTypeReference);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过key  获取 json 的值
     *
     * @param json
     * @return
     */

    public static String getJsonValue(String json, String key) {
        String value = "";
        try {
            JsonNode root = objectMapper.readTree(json);
            value = root.get(key).asText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

}

